<?php

class Servicedesk {
    
   static public function create_ticket(){
       global $dbdefault;
       
       $user_id = SESSION_value('user_id',0);
       $query_group=  sprintf("SELECT group_name FROM groups WHERE group_id=(SELECT group_id FROM users WHERE user_id=%d)",  qs($user_id));
       $res_total=mysql_query($query_group,$dbdefault) or die(mysql_error()."<br />".$qry);
       $group_name=mysql_result($res_total,0,'group_name');
       
       $user_name=POST_value('user_name','');
       $email_notify=POST_value('email_notify','');
       $contact_number=POST_value('contact_number','');
       $deadline=POST_value('deadline','');
       $start_time=POST_value('start_time','');
       $end_time=POST_value('end_time','');
       $technical=POST_value('technical','');
       $ticket_status=POST_value('ticket_status','1');
       $customer_name=POST_value('customer',$group_name);
       
       $device_type=POST_value('device_type','');
       $ticket_priority=POST_value('ticket_priority','');
       
       $subject=POST_value('subject','');
       $detail=POST_value('detail','');
       
       
       $start_t=date('Y-m-d H:i:s', strtotime($start_time));
       $end_t=date('Y-m-d H:i:s', strtotime($end_time));
       
       $filename=array();
       $mess="";
       if($_FILES['file']['name'][0]!=""){
           
            for($i=0;$i<count($_FILES["file"]['name']);$i++){
               if (file_exists(DOCUPLOADS ."/". $_FILES["file"]['name'][$i]))
                 {
                     $mess .= $_FILES["file"]['name'][$i] ." file exists, please change file name.<br>";
                     return $mess;
                 }
               else
                 {
                   $filename[]=  $_FILES["file"]["name"][$i];
                   move_uploaded_file($_FILES["file"]["tmp_name"][$i],
                     DOCUPLOADS ."/". $_FILES["file"]["name"][$i]);
                     $mess .= "Stored ". $_FILES["file"]["name"][$i]."<br>";
                 }
             }          
       }
       //upload thanh cong file
       $filename_todb="";
       if(count($filename)>0){
           $filename_todb = base64_encode(serialize($filename));
           //echo count($filename);
       }
       
       $time = strtotime($deadline);

        $newformat = date('Y-m-d',$time);
       
       $query=sprintf("insert into tickets (title, detail, author, createtime, ticketstatus, priority, 
           email_tonotify, mobile_toalert, attach_file, category_id, start_time, end_time, assigned, deadline,customer) 
           values(%s, %s, %d, CURRENT_TIMESTAMP, %d, %s, %s, %s, %s, %d, %s, %s, %d,%s,%s)", 
               qs($subject),  qs($detail), qs($user_id), qs($ticket_status), qs($ticket_priority),
 qs($email_notify), qs($contact_number),  qs($filename_todb),  qs($device_type),  qs($start_t),
 qs($end_t),  qs($technical),  qs($newformat),  qs($customer_name));
       
       //$mess.=$query;
       
       $res_user = mysql_query($query,$dbdefault);
       
       
        //$result= @mysql_query($query,$dbdefault);
        if (!$res_user){
            $mess.=" Insert to database failed <br>";
        }else{
            $mess.=" Insert to database successfuly <br>";
        }

//        $fromDatabase = unserialize(base64_decode($filename));

        return $mess;
   } 
    
   static public function create_log($logtype, $user_id, $detail, $module){
       global $dbdefault;
       $query=sprintf("insert into logs (log_type, user_id, log_detail, module) values(%s, %d, %s, %s)",  
               qs($logtype),  qs($user_id), qs($detail), qs($module));
       $res_user = mysql_query($query,$dbdefault) or die(__CLASS__.'->'.__METHOD__.':'.mysql_error());
   }
    
    static public function alert_user($user_id,$subject,$detail){
        global $dbdefault;
        $query=  sprintf("insert into alerts (alert_title, alert_content, alert_to_user) values(%s,%s,%d)",
        qs($subject), qs($detail), qs($user_id));
        $res_user = mysql_query($query,$dbdefault) or die(__CLASS__.'->'.__METHOD__.':'.mysql_error());
        
    }

    static public function alert_group($group_id,$subject, $detail){
        global $dbdefault;
        $query_user=  sprintf("SELECT user_id FROM users WHERE group_id=%d",  qs($group_id));
        $res_user = mysql_query($query_user,$dbdefault) or die(__CLASS__.'->'.__METHOD__.':'.mysql_error());
        $user=array();
        while($arr = mysql_fetch_assoc($res_user)){
            $user[] = $arr;            
        }
        if(count($user)){
            foreach($user as $u){
                Servicedesk::alert_user($u['user_id'], $subject,$detail);
            }            
        }
    }
    
    static public function notify_user($user_id,$request_id,$type){
        global $dbdefault;
        $query=sprintf("insert into notification (idrequest, user_id, notify_type) values(%d,%d,%s)",  
                qs($request_id), qs($user_id), qs($type) );
        $res_user = mysql_query($query,$dbdefault) or die(__CLASS__.'->'.__METHOD__.':'.mysql_error());
    }

    static public function notify_group($group_id,$request_id,$type){
        global $dbdefault;
        $query_user=  sprintf("SELECT user_id FROM users WHERE group_id=%d",  qs($group_id));
        $res_user = mysql_query($query_user,$dbdefault) or die(__CLASS__.'->'.__METHOD__.':'.mysql_error());
        $user=array();
        while($arr = mysql_fetch_assoc($res_user)){
            $user[] = $arr;            
        }
        if(count($user)){
            foreach($user as $u){
                Servicedesk::notify_user($u['user_id'], $request_id,$type);
            }            
        }
    }


    static public function create_configuration(){
      global $dbdefault;
       $config_name=POST_value('config_name','');
       $description=POST_value('description','');
       $device_customer=POST_value('device_customer','');
       $detail=POST_value('detail','');
       $device_list=POST_value('device_list','');
       $user=  SESSION_value("user_id");
       //echo $user;
       //echo $detail;
       $filename=array();
       $mess="";
       if($_FILES['file']['name'][0]!=""){
           
            for($i=0;$i<count($_FILES["file"]['name']);$i++){
               if (file_exists(CFGUPLOADS ."/". $_FILES["file"]['name'][$i]))
                 {
                     $mess .= $_FILES["file"]['name'][$i] ." file exists, please change file name.<br>";
                     return $mess;
                 }
               else
                 {
                   $filename[]=  $_FILES["file"]["name"][$i];
                   move_uploaded_file($_FILES["file"]["tmp_name"][$i],
                     CFGUPLOADS ."/". $_FILES["file"]["name"][$i]);
                     $mess .= "Stored ". $_FILES["file"]["name"][$i]."<br>";
                 }
             }          
       }
       //upload thanh cong file
       $filename_todb="";
       if(count($filename)>0){
           $filename_todb = base64_encode(serialize($filename));
           //echo count($filename);
       }
       if($device_list=='0'){
           $query=sprintf(" INSERT INTO configurations
                (configname, configdetail, config_file, user, description, idcustomer)
                 VALUE(%s,%s,%s,%d,%s,%d)",  qs($config_name), qs($detail), qs($filename_todb),
                qs($user), qs($description), qs($device_customer));
       }else{
           $query=sprintf(" INSERT INTO configurations
                (configname, configdetail, config_file, user, description, idcustomer, iddevice)
               VALUE(%s,%s,%s,%d,%s,%d,%d)",  qs($config_name), qs($detail), qs($filename_todb),
                qs($user), qs($description), qs($device_customer),  qs($device_list));
       }

            //echo $query;
        $result= @mysql_query($query,$dbdefault);
        if (!$result){
            $mess.=" Insert to database failed <br>";
        }else{
            $mess.=" Insert to database successfuly <br>";
        }

//        $fromDatabase = unserialize(base64_decode($filename));

        return $mess;
        
    }
    
    static public function delete_customer($c_id){
        global $dbdefault;
        $query="DELETE from customers WHERE idcustomers=$c_id";

        if($c_id==1){
            return array('success'=>FALSE,'error'=> "Can not delete service owner");
        }
        else {
            $result=@mysql_query($query,$dbdefault);
            if (!$result){
                echo mysql_error();
                return array('success'=>FALSE,'error'=> mysql_error());
            }else{
                return array('success'=>TRUE,'content'=>" is deleted");
            }
        }
    }
    
    static public function create($data){
        global $dbdefault;
        $r = User::validate($data);
        if ($r['success']) {
            $user_password = md5($data['user_password']);
            $query=sprintf(" INSERT INTO users
                (user_name,user_email,user_password,user_realname,user_created,group_id, idcustomer)
                VALUE(%s,%s,%s,%s,sysdate(),%d, %d) ",
                quote_smart($data['user_name']),quote_smart($data['user_email']),quote_smart($user_password),quote_smart($data['user_realname']),$data['group_id'],$data['idcustomer']);
            //echo $query;
            $result= @mysql_query($query,$dbdefault);
            if (!$result){
                return array('success'=>FALSE,'error'=> mysql_error(),'form_error'=>null);
            }else{
                return array('success'=>TRUE,'user_id'=>mysql_insert_id());
            }
        }else{
            //print_r($r);
            return array('success'=>FALSE,'error'=>$r['error'],'form_error'=>$r['form_error']);
        }
    }
    
    static public function validate($data,$mode='insert'){
        $error='';
        $form_error=array();
        $r = User::validate_username($data['user_name']);
        if (!$r['success']) {
            $error .= $r['error'].'<br/>';
            $form_error['user_name']=$r['error'];    
        }
        $r = User::validate_email($data['user_email'],$mode);
        if (!$r['success']) {
            $error .= $r['error'].'<br/>';
            $form_error['user_email']=$r['error'];    
        }
        $r = User::validate_password($data['user_password'],$data['user_password1']);
        if (!$r['success']) {
            $error .= $r['error'].'<br/>';
            $form_error['user_password']=$r['error'];    
        }
        if (empty($error)){
            return array('success'=>TRUE);
        }else{
            return array('success'=>FALSE,'error'=>'','form_error'=>$form_error);
        }
    }
    
    
}
?>
